﻿using CPPEI.Coolzon.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for DataSetWindow.xaml
    /// </summary>
    public partial class DataSetWindow : Window
    {
        public ServiceProxy.DesignServiceRef.DataSet RetDataSet { get; private set; }
        private Guid _DataSourceId;
        private bool _IsNew = false;
        private System.Collections.ObjectModel.ObservableCollection<ServiceProxy.DesignServiceRef.DataParameter> _paramList; 
        public DataSetWindow(Guid dataSourceId, ServiceProxy.DesignServiceRef.DataSet dataSet = null)
        {
            InitializeComponent();
            if (dataSet == null)
            {
                Title = "新建数据集";
                _IsNew = true;
                dataSet = new ServiceProxy.DesignServiceRef.DataSet();
                dataSet.Id = Guid.NewGuid();
                dataSet.Name = "新建数据集";
                dataSet.Caption = "新建数据集";
                dataSet.Type = "StoredProcedure";
            }
            else
            {
                Title = "修改数据集";
            }
            _DataSourceId = dataSourceId;
            RetDataSet = dataSet;
            _ctlGrid.DataContext = dataSet;
            _paramList = new System.Collections.ObjectModel.ObservableCollection<ServiceProxy.DesignServiceRef.DataParameter>();
            if (dataSet.Parameters != null && dataSet.Parameters.Length > 0)
            {
                foreach (var item in dataSet.Parameters)
                {
                    _paramList.Add(item);
                }
            }
            _ctlParameterList.ItemsSource = _paramList;

            Event.NCL.NCLEventBus.Register(this);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Event.NCL.NCLEventBus.Unregister(this);
        }

        private void _ctlAdd_Click(object sender, RoutedEventArgs e)
        {
            ServiceProxy.DesignServiceRef.DataParameter parameter = new ServiceProxy.DesignServiceRef.DataParameter();
            parameter.Id = Guid.NewGuid();
            parameter.Name = "新建参数";
            parameter.Caption = "新建参数";
            parameter.Type = "IN";

            _paramList.Add(parameter);
            _ctlParameterList.SelectedIndex = _ctlParameterList.Items.Count - 1;
        }

        private void _ctlRemove_Click(object sender, RoutedEventArgs e)
        {
            if (_ctlParameterList.SelectedItem != null)
            {
                if (MessageBox.Show("是否确定删除?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    _paramList.Remove(_ctlParameterList.SelectedItem as ServiceProxy.DesignServiceRef.DataParameter);
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_ctltbName.Text))
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("请输入名称");
                return;
            }

            RetDataSet.Id = (_ctlGrid.DataContext as ServiceProxy.DesignServiceRef.DataSet).Id;
            RetDataSet.Name = _ctltbName.Text;
            RetDataSet.Caption = _ctltbCaption.Text;
            RetDataSet.Type = _ctlType.SelectedItem.ToString();
            RetDataSet.ValueString = _ctltbValueString.Text;
            //if (_ctlcbCacheMode.SelectedItem != null)
            //{
                //RetDataSet.CacheMode = (Metadata.CacheMode)_ctlcbCacheMode.SelectedItem;
            //}
            RetDataSet.Parameters = new ServiceProxy.DesignServiceRef.DataParameter[_ctlParameterList.Items.Count];
            if (_ctlParameterList.Items != null && _ctlParameterList.Items.Count > 0)
            {
                int index = 0;
                foreach (var item in _ctlParameterList.Items)
                {
                    RetDataSet.Parameters[index++] = (item as ServiceProxy.DesignServiceRef.DataParameter);
                }
            }
            if (_IsNew)
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginCreateDataSetEvent(UIContext.Current.Token, _DataSourceId, RetDataSet, RetDataSet.Parameters));
            }
            else
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginUpdateDataSetEvent(UIContext.Current.Token, _DataSourceId, RetDataSet, RetDataSet.Parameters));
            }
            ProgressbarWindow.Instance.ShowProgress(true);
        }

        [Subscribe]
        public void EndCreateDataSetEvent(Event.NCL.EndCreateDataSetEvent @event)
        {
            ProgressbarWindow.Instance.Complete();
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowError(string.Format("创建数据集失败"));
                    Logger.ErrorToTag(Library.LogTAG, string.Format("创建数据集失败,{0}", @event.Error));
                });
            }
            else if(@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowInfo("创建成功");
                    DialogResult = true;
                });
            }
        }

        [Subscribe]
        public void EndUpdateDataSetEvent(Event.NCL.EndUpdateDataSetEvent @event)
        {
            ProgressbarWindow.Instance.Complete();
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowError(string.Format("更新数据集失败"));
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据集失败,{0}", @event.Error));
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowInfo("更新成功");
                    DialogResult = true;
                });
            }
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void _ctlParameterList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(_ctlParameterList.SelectedItem != null)
            {
                _ctlParameter.IsEnabled = true;
                _ctlParameter.DataContext = _ctlParameterList.SelectedItem as ServiceProxy.DesignServiceRef.DataParameter;
            }
            else
            {
                _ctlParameter.IsEnabled = false;
            }
        }

        private void _ctlType_Loaded(object sender, RoutedEventArgs e)
        {
            _ctlType.Items.Clear();
            _ctlType.Items.Add("StoredProcedure");
            _ctlType.Items.Add("Other");

            _ctlParamType.Items.Clear();
            _ctlParamType.Items.Add("IN");
            _ctlParamType.Items.Add("OUT");
        }
    }
}
